import React, { useEffect, useMemo, useState } from 'react';

import { useBoolean, useRequest } from 'ahooks';
import {
  Button,
  Divider,
  Dropdown,
  Form,
  Input,
  message,
  Modal,
  Select,
  Space,
  Table,
  Typography,
} from "antd";
import moment from "moment";
import Column from "antd/lib/table/Column";
import * as APIS from "../../../../constants/api-constants";
import { useFormik } from "formik";
import Detail from "./detail";
import Increase from "./increase";
import Axios from "axios";

import FileSaver from "file-saver";
import xlsx from "node-xlsx";
import Dragger from "antd/lib/upload/Dragger";
import { InboxOutlined } from "@ant-design/icons";
import axios from "axios";
const { Option } = Select;

const { Title } = Typography;

export default () => {
  const [isShow, { setTrue, setFalse }] = useBoolean(false);
  const [isClick, setClick] = useState(false);
  const [showDetail, setShowDetail] = useState(false);
  const [patentNumber, setPatentNumber] = useState('');
  const [exist, setExist] = useState(false);
  const { data: areaSelections } = useRequest(
    { url: APIS.GET_SELECTIONS, method: "GET" },
    {
      manual: false,
      formatResult: (response) => {
        return response?.data?.mainData?.applicationArea ?? [];
      },
    }
  );
  useEffect(() => {
    axios
      .get(APIS.CHECKPATENT, {
        params: { patentNumber },
      })
      .then((r) => {
        const { mainData, msg } = r.data;
        console.log(msg);
        console.log('checkExistMaindata:', mainData);
        setExist(mainData.state);
      })
      .catch(() => {
        alert('服务器异常');
      });
  }, [patentNumber]);

/*   const { data: talentSelections } = useRequest(
    {
      url: APIS.GET_TALENT_SELECTIONS,
      method: 'GET',
    },
    {
      formatResult: (response) => {
        return response?.data.mainData?.talents ?? [];
      },
    }
  ); */

  /**
   * 获取专利列表
   */
  const { data: patentsSource, run: refresh, loading: initLoading } = useRequest(
    {
      url: APIS.GET_PATENTS,
      method: 'GET',
    },
    {
      manual: false,
      formatResult: (response) => {
        return response?.data?.mainData?.patents ?? [];
      },
    }
  );

  /**
   * 删除专利
   */
  const { run: deleteWithId } = useRequest(
    (data) => {
      let { id } = data;
      return {
        url: `${APIS.DELETE_PATENT}?id=${id}`,
        method: 'DELETE',
      };
    },
    {
      manual: true,
      onError: (e) => {
        message.error("该专利和其他库有关联关系，无法删除！");
        message.destroy("deleting");
      },
    }
  );

  const formik = useFormik({
    initialValues: {
      patentName: '',
      applicationArea: '',
      type: '',
      organizations: [],
      talents: [],
      address: '',
      applicationNumber: '',
      applicationTime: '',
      currentOrganization: '',
      currentTalents: '',
      talentsString: '',
      publicNumber: '', // 公开号
      legalStatus: '',
      conversionMethod: '',
      conversionType: '',
      description: '',
      technicalAdvantages: '',
      applicationOrganization: [],
      addressBefore: [],
      fileList: [],
    },
    onSubmit: (values, actions) => {
      const formData = new FormData();
      console.log(values);
      formData.append("patentName", values.patentName);
      formData.append("applicationArea", values.applicationArea);
      formData.append(
        'applicationOrganization',
        values.applicationOrganization as any
      );
      formData.append("talents", values.talents as any);
      formData.append(
        "address",
        values.addressBefore.join(";") + ";" + values.address
      );
      formData.append("applicationNumber", values.applicationNumber);
      formData.append("type", values.type);
      values.applicationTime !== 'Invalid date' && values.applicationTime !== '' &&
        formData.append("applicationTime", values.applicationTime);
      formData.append("publicNumber", values.publicNumber);
      formData.append("legalStatus", values.legalStatus);
      formData.append("conversionMethod", values.conversionMethod);
      formData.append("conversionType", values.conversionType);
      formData.append("description", values.description);
      formData.append("technicalAdvantages", values.technicalAdvantages);
      formData.append(
        'file',
        values.fileList.length !== 0
          ? values.fileList[0]
          : new File([], 'null.pdf')
      );

      Axios.post(APIS.CREATE_PATENT, formData)
        .then((r) => {
          if (!r.data.mainData.exist) {
            setClick(false);
            setPatentNumber('');
            message.success('添加成功');
          } else {
            message.error(r.data.msg);
          }
        })
        .catch((e) => {
          message.error("添加失败");
        });
      actions.resetForm({
        patentName: '',
        applicationArea: '',
        type: '',
        organizations: [],
        talents: [],
        address: '',
        applicationNumber: '',
        applicationTime: null,
        currentOrganization: '',
        currentTalents: '',
        talentsString: '',
        publicNumber: '', // 公开号
        legalStatus: '',
        conversionMethod: '',
        conversionType: '',
        description: '',
        technicalAdvantages: '',
        applicationOrganization: [],
        fileList: [],
      } as any);
      setFalse();
      setTimeout(() => {
        refresh();
      }, 2000);
    },
  });

  const [curConversion, setCurConversion] = useState('');
  const [curArea, setCurArea] = useState('all');
  const [curName, setCurName] = useState('');
  const [curOrg, setCurOrg] = useState('');
  const [curDetailId, setCurDetailId] = useState<number>(0);
  const [curDetail, setCurDetail] = useState<any>({} as any);
  useEffect(() => { }, [curDetail]);

  const patents = useMemo(() => {
    let src: any[] = patentsSource ?? [];

    /**
     * 专利筛选查询
     */
    return src.filter((item: any) => {
      if (
        curConversion &&
        item.conversionType !== curConversion &&
        curConversion !== 'all'
      ) {
        return false;
      }

      if (
        curArea &&
        item.applicationAreaName !== curArea &&
        curArea !== 'all'
      ) {
        return false;
      }

      if (curName && !item.name.includes(curName)) {
        return false;
      }

      if (curOrg && !(item.applicationOrganization ?? '').includes(curOrg)) {
        return false;
      }

      return true;
    });
  }, [patentsSource, curConversion, curArea, curName, curOrg]);

  const [selectedKeys, setSelectedKeys] = useState<number[]>([]);
  const tmpArray = [
    '专利名称',
    '应用领域',
    '专利类型',
    '申请人',
    '发明人员',
    '转化方式',
    '转化状态',
    '地址',
    '法律状态',
    '公开号',
    '申请号',
    '申请日',
    '专利简介',
    '技术优势',
    '(前三行不可删除)',
  ];

  /**
   * 批量导入
   */
  const uploadProps: any = {
    name: 'file',
    action: APIS.UPLOAD_PATENTS,

    headers: { Authorization: localStorage.getItem("Authorization") },
    beforeUpload(file: File) {
      return new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsArrayBuffer(file);
        reader.onload = () => {
          if (reader.result && typeof reader.result !== 'string') {
            const buf = reader.result;
            const parse = xlsx.parse(buf, { type: "buffer" });
            const { data } = parse[0];
            let dataFilter = data;
            // .filter((v: any[], i: number) => {
            //   if (i !== 0 && i !== 2) {
            //     for (let index = 0; index <= 9; index++) {
            //       if (!v[index] || v[index] === 0) {
            //         return false;
            //       }
            //     }

            //     return true;
            //   }
            //   return true;
            // });
            if (JSON.stringify(data[0]) !== JSON.stringify(tmpArray)) {
              message.error(
                '上传文件中首行不正确请重试(请下载模板文件查看)',
                15
              );
            } else if (dataFilter.length !== data.length) {
              const blob = new Blob(
                [xlsx.build([{ name: "template", data: dataFilter }])],
                {
                  type: 'application/octet-stream',
                }
              );
              message.info('返回文件为上传的有效值', 15);
              resolve(blob);
              FileSaver.saveAs(blob, '有效值.xlsx');
            } else {
              const blob = new Blob(
                [xlsx.build([{ name: "template", data: dataFilter }])],
                {
                  type: 'application/octet-stream',
                }
              );
              message.success('文件检查通过,请等待后端验证并返回结果', 6);
              resolve(blob);
            }
          } else {
            message.error('文件读取失败请检查格式');
          }
        };
      });
    },
    onChange(info: {
      file: {
        response: { true: number; false: number; errorData: any[][] };
        status: string;
        name: any;
      };
      fileList: any;
    }) {
      if (info.file.status === 'done') {
        message.success(`${info.file.response.true}条专利上传成功。`);
        refresh();
        if (info.file.response.false > 0) {
          message.error(
            `${info.file.response.false}条专利上传失败，请在错误详情文件中查看`
          );

          const blob = new Blob(
            [
              xlsx.build([
                { name: "Financial", data: info.file.response.errorData },
              ]),
            ],
            {
              type: 'application/octet-stream',
            }
          );
          FileSaver.saveAs(blob, '错误详情.xlsx');
        }
      } else if (info.file.status === 'error') {
        message.error('上传失败');
      }
    },
  };
  const menu = (
    <div
      style={{
        background: 'rgb(251,251,251)',
        boxShadow: '3px 3px 3px 3px rgb(193,193,195)',
        borderRadius: '3px',
      }}
    >
      <Button
        style={{
          overflow: 'hidden',
          whiteSpace: 'normal',
          wordBreak: 'break-all',
          fontSize: '0.9rem',
          padding: '0',
          width: '10vw',
          height: 'auto',
          marginBottom: '2vh',
        }}
        onClick={() => {
          const data: string[][] = [
            [
              '专利名称',
              '应用领域',
              '专利类型',
              '申请人',
              '发明人员',
              '转化方式',
              '转化状态',
              '地址',
              '法律状态',
              '公开号',
              '申请号',
              '申请日',
              '专利简介',
              '技术优势',
              '(前三行不可删除)',
            ],
            [
              '必填，请输入专利名称',
              '	必填，请在（外科医学，体外诊断，康复工程）中选一项填写',
              '必填，请在（发明，实用新型，外观设计）中选一项填写',
              '必填，请填写专利申请人，多个申请人用英文;分割。（示例：公司A;公司B;）',
              '请填写专利发明人员，多个发明人员用英文;分割。示例（张三;赵四;）',
              '请在（产权买断，技术转让，未确定）中选一项填写',
              '必填，请在（已转化，待转化，未确定）中选一项填写',
              '请填写地址（地址格式为：xx省;xx市;xx区;xxx）',
              '必填，请在（公开，授权）中选一项填写',
              '请填写专利公开号',
              '	请填写申请号',
              '示例：2018/8/8',
              '必填，请填写专利简介（300字以内）',
              '必填，请填写专利技术优势（300字以内',
            ],
            ['请从下一行开始填写导入数据'],
          ];

          const blob = new Blob([xlsx.build([{ name: "Financial", data }])], {
            type: "application/octet-stream",
          });
          FileSaver.saveAs(blob, '导入模板.xlsx');
        }}
      >
        下载导入模板
      </Button>
      <Dragger accept={".xlsx"} {...uploadProps}>
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">请拖拽.XLSX文件至此或使用点击上传</p>
        <p className="ant-upload-hint">
          支持单次或批量上传。 严禁上传公司资料或其他公司文件
        </p>
      </Dragger>
    </div>
  );
  return (
    <>
      <div>
        <Title level={4}>筛选查询</Title>
      </div>
      <Form layout="inline">
        <Form.Item name="name">
          <Input
            placeholder="专利名称"
            value={curName}
            onChange={(e) => setCurName(e.target.value)}
          />
        </Form.Item>
        <Form.Item name="organization">
          <Input
            placeholder="申请人"
            value={curOrg}
            onChange={(e) => setCurOrg(e.target.value)}
          />
        </Form.Item>
        <Form.Item name="applacationArea" label="应用领域">
          <Select
            style={{ width: "100px" }}
            defaultValue="all"
            onSelect={(e: any) => {
              setCurArea(e);
            }}
            allowClear
          >
            <Option value="all" key="0">
              全部
            </Option>
            {(areaSelections ?? []).map((item: any) => (
              <Option key={item.uuid} value={item.name}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="state" label="转化状态">
          <Select
            defaultValue="all"
            style={{ width: "100px" }}
            onSelect={(e: any) => setCurConversion(e)}
            allowClear
          >
            <Option value="all" key="0">
              全部
            </Option>
            <Option value="待转化" key="1">
              待转化
            </Option>
            <Option value="已转化" key="2">
              已转化
            </Option>
            <Option value="未确定" key="3">
              未确定
            </Option>
          </Select>
        </Form.Item>
      </Form>
      <Divider orientation="left"></Divider>
      <h2 style={{ fontWeight: "bold", display: "inline-block" }}>详细信息</h2>
      {
        window.localStorage.getItem('identity') === null ?
          null
          :
          <Space style={{ float: "right" }}>
            <Dropdown
              trigger={["click"]}
              placement="bottomCenter"
              arrow
              overlay={menu}
            >
              <Button type="primary">批量导入</Button>
            </Dropdown>
            <Button type="primary" onClick={setTrue}>
              添加专利
            </Button>
          </Space>
      }
      <Table
        loading={initLoading}
        rowSelection={{
          onChange: (e) => {
            setSelectedKeys(e as any);
          },
          selectedRowKeys: selectedKeys,
        }}
        dataSource={patents}
        size="middle"
        rowKey="id"
        footer={() => {
          return (
            <>
              {
                window.localStorage.getItem('identity') === null ?
                  null
                  :
                  <Space>
                    <Button
                      onClick={() => {
                        if (patentsSource) {
                          const data: string[][] = [
                            [
                              '专利名称',
                              '专利类型',
                              '申请号',
                              '公开号',
                              '地址',
                              '应用领域',
                              '转化方式',
                              '转化状态',
                              '申请人',
                              '发明人',
                              '法律状态',
                              '地址',
                              '专利描述',
                              '技术优势',
                            ],
                          ];
                          const rowToBeExported = patentsSource.filter((item: any) =>
                            selectedKeys.includes(item.id)
                          );
                          rowToBeExported.forEach((item: any) => {
                            if (item) {
                              /* let curTalentsString = '';
                              item.talents.forEach((element: any) => {
                                curTalentsString += element.name + ';';
                              });
                              curTalentsString += item.talentsString; */
                              data.push([
                                item.name,
                                item.type,
                                item.applicationNumber,
                                item.publicNumber,
                                item.address,
                                item.applicationAreaName,
                                item.conversionMethod,
                                item.conversionType,
                                item.applicationOrganization,
                                item.talentsString,
                                item.legalStatus,
                                item.address,
                                item.description,
                                item.technicalAdvantages,
                              ]);
                            }
                          });
                          if (data.length !== 1) {
                            const blob = new Blob(
                              [xlsx.build([{ name: "output", data }])],
                              {
                                type: 'application/octet-stream',
                              }
                            );
                            FileSaver.saveAs(blob, '专利信息导出表.xlsx');
                          }
                        }

                      }}
                    >
                      批量导出
                    </Button>
                    <Button
                      onClick={async () => {
                        message.loading({
                          content: '删除中',
                          key: 'deleting',
                          duration: 0,
                        });

                        for (let key of selectedKeys) {
                          await deleteWithId({ id: key });
                        }

                        message.destroy('deleting');
                        refresh();
                      }}
                    >
                      批量删除
                    </Button>
                  </Space>
              }
            </>
          );
        }}
      >
        <Column title="名称" dataIndex="name" key="name" />
        <Column
          title="申请人"
          dataIndex="applicationOrganization"
          key="applicationOrganization"
        />
        <Column
          title="专利类型"
          dataIndex="type"
          key="type"
        />
        <Column
          title="法律状态"
          dataIndex="legalStatus"
          key="legalStatus"
        />
        <Column
          title="应用领域"
          dataIndex="applicationAreaName"
          key="applicationAreaName"
        />
        <Column
          title="转化状态"
          dataIndex="conversionType"
          key="conversionType"
        />
        {
          window.localStorage.getItem('identity') === null ?
            <Column
              title="操作"
              dataIndex="operation"
              key="operation"
              render={(_text: string, record: any) => (
                <Space size={10}>
                  <Button
                    type="link"
                    onClick={() => {
                      console.log(record);
                      setCurDetailId(record.id);
                      setShowDetail(true);
                      setCurDetail({
                        description: record.description,
                        technicalAdvantages: record.technicalAdvantages,
                      } as any);
                    }}
                  >
                    详情
                  </Button>
                </Space>
              )}
            />
            :
            <Column
              title="操作"
              dataIndex="operation"
              key="operation"
              render={(_text: string, record: any) => (
                <Space size={10}>
                  <Button
                    type="link"
                    onClick={() => {
                      console.log(record);
                      setCurDetailId(record.id);
                      setShowDetail(true);
                      let add = "";
                      let before: string[] = [];
                      if (record.address) {
                        const address = record.address?.split(";");
                        const adr = address.pop();
                        if (adr) {
                          add = adr;
                          before = address;
                        }
                      }
                      setCurDetail({
                        patentName: record.name,
                        applicationArea: record.application_area.uuid,
                        currentOrganization: record.applicationOrganization,
                        type: record.type,
                        currentTalents: record.talentsString,
                        address: add,
                        addressBefore: before,
                        publicNumber: record.publicNumber,
                        applicationNumber: record.applicationNumber,
                        applicationTime: record.applicationTime?.split('T')[0]
                          ? moment(
                            record.applicationTime.split('T')[0],
                            'YYYY-MM-DD'
                          )
                          : null,
                        legalStatus: record.legalStatus,
                        conversionMethod: record.conversionMethod,
                        conversionType: record.conversionType,
                        description: record.description,
                        technicalAdvantages: record.technicalAdvantages,
                      } as any);
                    }}
                  >
                    详情
                  </Button>
                  <Button
                    type="link"
                    onClick={async () => {
                      await deleteWithId({ id: record.id });
                      refresh();
                    }}
                  >
                    删除
                  </Button>
                </Space>
              )}
            />
        }
      </Table>
      <Modal
        visible={isShow}
        title="添加专利信息"
        onOk={() => {
          setTrue();
        }}
        onCancel={() => {
          setFalse();
          setClick(false);
          setPatentNumber('');
        }}
        destroyOnClose
        footer={false}
        width={"70vw"}
        style={{ top: 15 }}
      >
        <Increase
          formik={formik}
          isClick={isClick}
          setClick={setClick}
          setFalse={setFalse}
          areaSelections={areaSelections}
          // talentSelections={talentSelections}
          setPatentNumber={setPatentNumber}
          exist={exist}
        />
      </Modal>

      <Modal
        visible={showDetail}
        title="查看专利信息"
        onOk={() => setShowDetail(true)}
        onCancel={() => setShowDetail(false)}
        destroyOnClose
        footer={false}
        width={"70vw"}
        style={{ top: 15 }}
      >
        <Detail
          refresh={refresh}
          curDetail={curDetail}
          curDetailId={curDetailId}
          areaSelections={areaSelections}
          setFalse={() => setShowDetail(false)}
        />
      </Modal>
    </>
  );
};
